package com.yupi.springbootinit.bizmq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.enums.ChartStatusEnum;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.sse.SseService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

import static com.yupi.springbootinit.constant.CommonConstant.YUCONGMING_AI_MODE_ID;

@Component
@Slf4j
public class BIMessageConsumer {

    @Resource
    ChartService chartService;
    @Resource
    AiManager aiManager;
    @Resource
    SseService sseService;

    @SneakyThrows
    @RabbitListener(queues = {BIMQConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        if (StringUtils.isBlank(message)) {
            //失败，拒绝消息
            //            channel.basicNack(deliveryTag,false,false);
            channel.basicReject(deliveryTag, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "队列消息未接收");
        }
        long id = Long.parseLong(message);
        Chart chart = chartService.getById(id);
        if (chart == null) {
            //            channel.basicNack(deliveryTag,false,false);
            channel.basicReject(deliveryTag, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表不存在");
        }
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(ChartStatusEnum.RUNNING.getValue());


        boolean b = chartService.updateById(updateChart);
        if (!b) {
            //            channel.basicNack(deliveryTag,false,false);
            channel.basicReject(deliveryTag, false);
            handleChartUpdateError(chart.getId(), "更新图表'执行中'状态失败");
            return;
        }
        //发送执行中状态
        sseService.sendChartStatusMessage(updateChart);
        //调用ai
        String analyzeResult;
        String userInputMsg = userInput(chart);
        log.info("用户输入数据：{}",userInputMsg);
        try {
            analyzeResult = aiManager.doChat(YUCONGMING_AI_MODE_ID,userInputMsg);
        } catch (BusinessException e) {
            log.error(e.getMessage());
            channel.basicReject(deliveryTag, false);
            handleChartUpdateError(chart.getId(), e.getMessage());
            return;
        }
        if ("".equals(analyzeResult)) {
            channel.basicReject(deliveryTag, false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }
        String[] split = analyzeResult.split("【【【【【");
        if (split.length < 3) {
            //            channel.basicNack(deliveryTag,false,false);
            channel.basicReject(deliveryTag, false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }
        String genChart = split[1].trim().replaceAll("'", "\"");
        String genResult = split[2].trim();
        //调用ai得到结果之后,再更新一次
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus(ChartStatusEnum.SUCCEED.getValue());
        boolean b1 = chartService.updateById(updateChartResult);
        if (!b1) {
            //            channel.basicNack(deliveryTag,false,false);
            channel.basicReject(deliveryTag, false);
            handleChartUpdateError(chart.getId(), "更新图表'成功'状态失败");
        }
        //发送成功状态
        sseService.sendChartStatusMessage(updateChartResult);
        //关闭sse连接
        SseEmitter sseEmitter = sseService.getSseEmitterPool().get(String.valueOf(chart.getId()));
        if (sseEmitter != null) {
            sseEmitter.complete();
        }
        //手动确认ack
        channel.basicAck(deliveryTag, false);
    }

    private String userInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvString = chart.getChartData();
        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        //拼接图标类型
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += goal + ",请使用" + chartType + "图标类型";
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvString).append("\n");
        return userInput.toString();
    }

    private void handleChartUpdateError(long chartId, String execMsg) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ChartStatusEnum.FAILED.getValue());
        updateChartResult.setExecMessage(execMsg);
        boolean save = chartService.saveOrUpdate(updateChartResult);
        if (!save) {
            log.error("更新图表'失败'状态失败" + chartId + "," + execMsg);
        }
        //发送失败状态
        sseService.sendChartStatusMessage(updateChartResult);
        //关闭sse连接
        SseEmitter sseEmitter = sseService.getSseEmitterPool().get(String.valueOf(chartId));
        if (sseEmitter != null) {
            sseEmitter.complete();
        }
    }
}
